package demo.Thread;

import java.util.Arrays;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/9-08-09-14:57
 * @Description：demo.Thread  线程组
 */
/*
线程组：
    统一管理同组的线程
main线程所在的线程组也为main
自己创建的线程默认线程组的名称为main
 */
public class Thread_group {
    public static void main(String[] args) {
        ThreadGroup group = Thread.currentThread().getThreadGroup();    //获取main线程所在的线程组
        System.out.println("Group.name: " + group.getName());        //Group.name: main

        new Thread(){
            @Override
            public void run() {
                System.out.println("thread-0.Group.name: " + Thread.currentThread().getThreadGroup().getName());     //thread-0.Group.name: main
            }
        }.start();
        //手动指定线程组
        ThreadGroup threadGroup = new ThreadGroup("hjy");
        Thread thread2 = new Thread(threadGroup,"thread2"){
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
                System.out.println("thread2Group = " + Thread.currentThread().getThreadGroup().getName());
            }
        };
        thread2.start();
        System.out.println(threadGroup.activeCount());      //获取该组线程的存活数量
        Thread[] threadArr = new Thread[threadGroup.activeCount()];
        threadGroup.enumerate(threadArr);                   //将线程组的线程 复制给 线程数组
        System.out.println(Arrays.toString(threadArr));

        //不推荐使用stop() ，可能会造成死锁
        group.stop();         //停止线程组中所有的线程
        //group.setDaemon();    给线程组设置为守护进程，不是给线程组中所有进程设置为守护进程
    }
}
